<script>
let arapComponent =  {
        template: `
<div id="tallyRecordBox">
    <div class="el-row">
        <div class="el-col el-col-12 el-col-xs-24">
            <div style="background: rgb(241, 82, 58);position: relative;border-radius: 4px;padding: 20px;margin: 0 5px;height: 140px;box-sizing: border-box;color: #fff;font-size: 14px;">
                <h1 style="font-size:32px;font-weight: bold;">{{ counts.inRemain }}</h1>
                <div class="value">应收余额 (历史累计)
                    <el-tooltip placement="top">
                      <div slot="content">统计规则：<br/>
                        应收（付）：历史累计创建的应收付账单金额<br/>
                        已收（付）：历史累计创建的核销记录金额<br/>
                        该统计数据统计范围为从账套创建开始到当前时间，为历史累计统计。
                      </div>
                      <i class="el-icon-warning-outline"></i>
                    </el-tooltip>
                </div>
                <hr />
                <span style="float:left">应收总额：{{ counts.inAll }}</span>
                <span style="float:right">已收金额：{{ counts.inAlready }}</span>
            </div>
        </div>
        <div class="el-col el-col-12 el-col-xs-24">
            <div style="background: rgb(103, 194, 58);position: relative;border-radius: 4px;padding: 20px;margin: 0 5px;height: 140px;box-sizing: border-box;color: #fff;font-size: 14px;">
            <h1 style="font-size:32px;font-weight: bold;">{{ counts.outRemain }}</h1>
                <div class="value">应付余额 (历史累计)
                    <el-tooltip placement="top">
                      <div slot="content">统计规则：<br/>
                        应收（付）：历史累计创建的应收付账单金额<br/>
                        已收（付）：历史累计创建的核销记录金额<br/>
                        该统计数据统计范围为从账套创建开始到当前时间，为历史累计统计。<br/>
                        未通过审核的账单不进行统计
                      </div>
                      <i class="el-icon-warning-outline"></i>
                    </el-tooltip>
                </div><hr />
                <span style="float:left">应付总额：{{ counts.outAll }}</span>
                <span style="float:right">已付金额：{{ counts.outAlready }}</span>
            </div>
        </div>
        
   </div>
    <div class="tallyRecordForm">
        <div class="recordListBox">
            <el-card class="box-card" style="cursor: initial;">
                <div slot="header" class="clearfix">
                    <el-row>
                        <el-col :span="10">
                            <span>挂账清单</span>
                            <el-divider direction="vertical"></el-divider>
                            <span>{{ recordPeriod }}</span>
                        </el-col>
                        <el-col :span="14" style="color:#3f51b5;">
                            <span>
                            （该时间区间内）应收：<b>{{countPeriod['inAll']}}</b> 已收：<b>{{countPeriod['inOver']}}</b>
                            </span>
                            <el-divider direction="vertical"></el-divider>
                            <span>
                            应付：<b>{{countPeriod['outAll']}}</b>  已付：<b>{{countPeriod['outOver']}}</b>
                            </span>
                            <el-tooltip placement="top">
                              <div slot="content">统计规则：<br/>
                                应收（付）：筛选时间段内创建的应收付账单金额统计<br/>
                                已收（付）：筛选时间段内进行的应收（付）核销记录金额统计<br/>
                                由于核销操作存在滞后性，某一时间段内应收（付）与已收（付）金额不一致属正常情况。<br/>
                                未通过审核的账单不进行统计
                              </div>
                              <i class="el-icon-warning-outline"></i>
                            </el-tooltip>
                        </el-col>
                    </el-row>
                </div>
                <div class="recordSearchBox" style="cursor: initial;">
                    <el-form :inline="true" v-model="recordSearchForm" class="form-inline recordSearchForm">
            <el-form-item size="mini">
            <el-select placeholder="全部状态" clearable filterable default-first-option v-model="recordSearchForm.state" @change="selectDisposeCode" filterable>
            <el-option
            v-for="item in tallyStates"
            :key="item.id"
            :label="item.title"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
            <el-select placeholder="全部类型" clearable filterable default-first-option v-model="recordSearchForm.type" @change="recordSearchForm.category_id='';" filterable>
            <el-option
            v-for="item in tallyTypes"
            :key="item.id"
            :label="item.title"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
             <el-cascader
                     collapse-tags clearable
                     v-model="recordSearchForm.category_id"
                     :options="categoryListForOptions"></el-cascader>
            </el-form-item>
            <el-form-item size="mini">
            <el-select   placeholder="全部账户" multiple  collapse-tags clearable filterable default-first-option v-model="recordSearchForm.accounts" @change="selectDisposeCode">
            <el-option
            v-for="item in accountList"
            :key="item.id"
            :label="item.title"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
            <el-select placeholder="客户/供应商" multiple  collapse-tags clearable filterable default-first-option v-model="recordSearchForm.stores" @visible-change="checkCateValid" @change="selectDisposeCode">
            <el-option
            v-for="item in storeList"
            :key="item.id"
            :label="item.title"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
            <el-select multiple  collapse-tags placeholder="项目" clearable filterable default-first-option v-model="recordSearchForm.projects" @change="selectDisposeCode">
            <el-option
            v-for="item in projectList"
            :key="item.id"
            :label="item.title"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
            <el-select multiple  collapse-tags  placeholder="员工" clearable filterable default-first-option v-model="recordSearchForm.members" @change="selectDisposeCode">
            <el-option
            v-for="item in memberList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
            </el-option>
            </el-select>
            </el-form-item>
            <el-form-item size="mini">
            <el-date-picker class="datePicker" type="date" value-format="yyyy-MM-dd" placeholder="开始日期" v-model="recordSearchForm.begin_date"></el-date-picker>
            ~
            <el-date-picker class="datePicker" type="date" value-format="yyyy-MM-dd" placeholder="结束日期" v-model="recordSearchForm.end_date"></el-date-picker>
            </el-form-item>
            <el-form-item size="mini">
            <el-input placeholder="备注关键字" v-model="recordSearchForm.memo"></el-input>
            </el-form-item>
            <el-button type="primary" size="mini" @click="searchArap"><i class="el-icon-search" /> 检索</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="success" size="mini" @click="exportRecordList()"><i class="el-icon-download" />  导出</el-button>
            <!--
            <el-button type="primary" size="mini" @click="getRecordList(1)">最近三个月</el-button>-->
        </el-form>
        </div>
        <div class="recordTable">
        <template>
        <el-table :data="recordList" border stripe  style="cursor: initial;">
        <el-table-column fixed type="index">
        </el-table-column>
        <el-table-column fixed prop="tally_time" sortable width="150" label="账单日期">
        <template slot-scope="scope">
        <p><i class="el-icon-time"></i>
        <span>{{ scope.row.tally_time.substring(0,10) }}</span>
        </p>
        <p>{{ scope.row.type_txt}} -{{ scope.row.category_name }} </p>
        </template>
        </el-table-column>
        <el-table-column prop="account_name" label="总金额">
        <template slot-scope="scope">
        <p v-if="scope.row.type==10" class="amount-in">
        <span>{{ scope.row.amount }}</span>
        </p>
        <p v-if="scope.row.type==20" class="amount-out">
        <span>{{ scope.row.amount }}</span>
        </p>
        </template>
        </el-table-column>
        <el-table-column prop="account_name1" label="未核销">
        <template slot-scope="scope">
        <p v-if="scope.row.type==10" class="amount-in">
        <span>{{ scope.row.amount_remain }}</span>
        </p>
        <p v-if="scope.row.type==20" class="amount-out">
        <span>{{ scope.row.amount_remain }}</span>
        </p>
        </template>
        </el-table-column>
        <el-table-column prop="account_name" label="累计核销">
        <template slot-scope="scope">
        <p v-if="scope.row.type==10" class="amount-in">
        <span>{{ scope.row.all_price }}</span>
        </p>
        <p v-if="scope.row.type==20" class="amount-out">
        <span>{{ scope.row.all_price }}</span>
        </p>
        </template>
        </el-table-column>


        <el-table-column prop="account_name" label="当月核销">
        <template slot-scope="scope">
        <p v-if="scope.row.type==10" class="amount-in">
        <span>{{ scope.row.now_price }}</span>
        </p>
        <p v-if="scope.row.type==20" class="amount-out">
        <span>{{ scope.row.now_price }}</span>
        </p>
        </template>
        </el-table-column>
        <el-table-column prop="store_name" width="100px" label="客户/供应商"></el-table-column>
        <el-table-column prop="project_name" label="项目"></el-table-column>
        <el-table-column prop="member_name" label="员工"></el-table-column>
        <el-table-column prop="memo" label="备注"></el-table-column>
        <el-table-column prop="extra" label="附件">
        <template slot-scope="scope">
        <span v-for="(item,iai) in scope.row.attachment" >
        <a :href="item.file_name" target="_blank" class="attachLink">
        附{{ ++iai }}
        </a>&nbsp;
        </span>
        </template>
        </el-table-column>
        <el-table-column prop="state_txt" label="状态">
        <template slot-scope="scope">
            <span v-if="scope.row.state == '0'">
                <el-tag type="info" size="mini">{{scope.row.state_txt}}</el-tag>
                <div v-if="scope.row.state==0 && currentTally.role!='accountant'" style="display: inline-block;margin-left:6px;">
                    <span class="recordOptBtn primary" @click="auditRecord(scope.row,1)">
                    <i class="el-icon-check"></i>&nbsp;</span>
                    <span class="recordOptBtn primary" @click="auditRecord(scope.row,-1)">
                    <i class="el-icon-close"></i>&nbsp;
                    </span>
                </div>
            </span>
            <el-tag v-if="scope.row.state == '1'" type="primary" size="mini">{{scope.row.state_txt}}</el-tag>
            <el-tag v-if="scope.row.state == '2'" type="warning" size="mini">{{scope.row.state_txt}}</el-tag>
            <el-tag v-if="scope.row.state == '3'" type="success" size="mini">{{scope.row.state_txt}}</el-tag>
            <el-tag v-if="scope.row.state == '-1'" type="danger" size="mini">{{scope.row.state_txt}}</el-tag>
        </template>
        </el-table-column>
        <el-table-column fixed="right" width="150" label="操作" v-if="currentTally.role!='viewer' ">
        <template slot-scope="scope">
           <el-dropdown v-if="scope.row.state==1||scope.row.state==2" size="medium" split-button type="primary" class="recOpt" @click="addArap(scope.row)" trigger="click" @command="handleCommand">
                <i class="el-icon-document-checked"></i>&nbsp;核销&nbsp;
            <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-if="scope.row.state==1||scope.row.state==2" :command="composeValue('editRecord',scope.row)"><i class="el-icon-edit"></i>&nbsp;编辑</el-dropdown-item> 
            <el-dropdown-item :command="composeValue('detailArap',scope.row)"><i class="el-icon-tickets"></i>&nbsp;查看明细</el-dropdown-item>
            <el-divider></el-divider>
            <el-dropdown-item v-if="currentTally.role!='cashier' && currentTally.role!='viewer' " :command="composeValue('delRecord',scope.row,scope.$index)">  <i class="el-icon-delete-solid"></i>&nbsp;删除</el-dropdown-item>
            </el-dropdown-menu>
            </el-dropdown>
            <el-button v-if="scope.row.state==3" @click="detailArap(scope.row)" trigger="click" @command="composeValue('detailArap',scope.row)" size="mini" type="primary"><i class="el-icon-tickets"></i>&nbsp;查看明细</el-button>
        </template>
        </el-table-column>
    </el-table>

        <p style="margin-top: 10px;text-align: center">
        <el-pagination
        background
        layout="prev, pager, next, total"
        :page-size="recordListPage.pageSize"
        :total="recordListPage.totalCount"
        @current-change="handleRecordPageChange"
        >
        </el-pagination>
        </p>
        </template>
        </div>
        </el-card>
        </div>
    </div>
    <!--账单编辑表单框------>
    <record-form :dialogShow="recordDialog" :formRow="recordForm" @modalClose="modalClose" @getRecordList="getRecordList"></record-form>
    <!--核销条目表单框------>
    <arap-form :dialogShow="arapDialog" :formRow="arapForm" @modalClose="arapDialog=false" @getRecordList="getRecordList"></arap-form>
    <!--核销列表框------>
    <arap-details :dialogShow="arapDetailsDialog" :arapId="arapId" :arapRow="arapRow" @modalClose="arapDetailsDialogClose"></arap-details>
</div>
    `,
        computed: {
            currentTallyId() {
                return this.$store.state.currentTallyId
            },
            currentTally () {
                return this.$store.state.currentTally
            },
            customList () {
                return this.$store.state.customList
            },
            gysList () {
                return this.$store.state.gysList
            },
            storeList() {
                if(this.recordSearchForm.type===10) return this.customList
                if(this.recordSearchForm.type===20) return this.gysList
            },
            categoryListIn() {
                return this.$store.state.categoryListIn
            },
            categoryListOut() {
                return this.$store.state.categoryListOut
            },
            categoryList() {
                if(this.recordSearchForm.type===10) return this.categoryListIn
                if(this.recordSearchForm.type===20) return  this.categoryListOut
                return []
            },
            accountList() {
                return this.$store.state.accountList
            },
            projectList() {
                return this.$store.state.projectList
            },
            memberList() {
                return this.$store.state.memberList
            },
            categoryListForOptions(){


                let options = []
                let origin_datas = this.categoryList;

                for (let i=0;i<origin_datas.length;i++){
                    if(origin_datas[i]['children']===undefined){
                        continue;
                    }
                    let itemData = {
                        'label':origin_datas[i]['title'],
                        'value':origin_datas[i]['id'],
                        'children':[]
                    };
                    for (let a = 0;a<origin_datas[i]['children'].length;a++){
                        let itemVItem = {
                            'label':origin_datas[i]['children'][a]['title'],
                            'value':origin_datas[i]['children'][a]['id'],
                        };
                        if(origin_datas[i]['children'][a]['children'] !== undefined){
                            itemVItem['children'] = [];
                            for (let z=0;z<origin_datas[i]['children'][a]['children'].length;z++){
                                itemVItem['children'].push({
                                    'label':origin_datas[i]['children'][a]['children'][z]['title'],
                                    'value':origin_datas[i]['children'][a]['children'][z]['id'],
                                });
                            }
                        }
                        itemData['children'].push(itemVItem);
                    }
                    options.push(itemData);
                }
                console.log(options)
                return options;
            },
        },
        data:function(){
            return {
                recordDialog:false,
                recordForm:{},
                arapDialog:false,
                arapDetailsDialog:false,
                arapForm:{},
                arapId:0,
                arapRow:{},
                currentPage:1,
                recordPeriod: monthBeginDate + ' ～ '+monthEndDate,
                recordSearchForm:{
                    begin_date : monthBeginDate,
                    end_date : monthEndDate,
                },
                tallyTypes:[{id:10,title:'应收款'},{id:20,title:'应付款'}],
                tallyStates:[
                    {id:0,title:'待审核'},
                    {id:1,title:'待核销'},
                    {id:2,title:'核销中'},
                    {id:3,title:'核销完毕'}
                ],
                recordList:[],
                recordListPage:{
                    pageSize:10,
                    totalCount:0,
                },
                counts:{
                    inRemain:0,
                    outRemain:0,
                },
                countPeriod:{} , // 区间内的应收付统计
            }
        },
        mounted () {
            this.initData()
        },
        methods:{
            initData() {
                this.getRecordList()
                this.getCount()
                this.getCountPeriod()
            },
            modalClose(){
                this.recordDialog = false
                this.getRecordList()
            },
            selectDisposeCode(){
                console.log('777')
                this.$forceUpdate()
            },
            arapDetailsDialogClose() {
                this.arapDetailsDialog=false
                this.getRecordList()
            },
            handleRecordPageChange(currentPage){
                this.currentPage = currentPage
                this.getRecordList(0)
            },
            searchArap(){
                this.getRecordList(0)
                this.getCountPeriod()
            },
            checkCateValid(viState){
                if(viState && !this.recordSearchForm.type) {
                    this.$message({
                        type: 'info',
                        message: '请先选择类型'
                    })
                }
            },
            getRecordList(an){
                let that = this
                const page = this.currentPage
                if(an === 1) {
                    that.recordSearchForm = {
                        begin_date : monthBeginDate,
                        end_date : monthEndDate,
                    }
                }
                if(that.recordSearchForm['category_id'] != undefined){
                    that.recordSearchForm['category_id'] = that.recordSearchForm['category_id'][that.recordSearchForm['category_id'].length-1];
                }
                that.recordSearchForm.tally_id = that.currentTallyId
                that.recordSearchForm.page = page
                axios.get('/api/tally-arap/lists',{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: that.recordSearchForm
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        that.recordList = res.data.data.data
                        that.recordPeriod = that.recordSearchForm.begin_date + ' ～ '+ that.recordSearchForm.end_date
                        that.recordListPage = res.data.data.pageInfo
                    }else{
                        that.$message({
                            type: 'error',
                            message: '解析数据失败:'+res.data.error_message
                        })
                    }
                })
            },
            getCount(){
                let that = this
                axios.get('/api/tally-arap/count',{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: that.recordSearchForm
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        that.counts = res.data.data
                    }else{
                        that.$message({
                            type: 'error',
                            message: '解析数据失败:'+res.data.error_message
                        })
                    }
                })
            },
            getCountPeriod(){
                let that = this
                axios.get('/api/tally-arap/count-period',{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: that.recordSearchForm
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        that.countPeriod = res.data.data
                    }else{
                        that.$message({
                            type: 'error',
                            message: '解析数据失败:'+res.data.error_message
                        })
                    }
                })
            },
            exportRecordList(){
                let that = this
                that.recordSearchForm.tally_id = that.currentTallyId
                axios.get('/api/tally-arap/export',{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: that.recordSearchForm
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        let filepath = res.data.data.filepath
                        let a = document.createElement('a');
                        a.target = "_blank";
                        a.href = filepath;
                        a.click();
                        console.log(res.data)
                    }else{
                        that.$message({
                            type: 'error',
                            message: '解析数据失败:'+res.data.error_message
                        })
                    }
                })
            },
            composeValue(act, row, ext) {
                return {
                    'act': act,
                    'row': row,
                    'ext': ext || ''
                }
            },
            handleCommand(command) {
                const row = command['row']
                switch (command['act']) {
                    case 'delRecord':
                        this.delRecord(command['ext'],row)
                        break;
                    case 'editRecord':
                        this.editRecord(row)
                        break;
                    case 'auditRecord':
                        this.auditRecord(row,command['ext'])
                        break;
                    case 'addArap':
                        this.addArap(row)
                        break;
                    case 'detailArap':
                        this.detailArap(row)
                        break;
                    default:
                        break;
                }
            },
            addArap(row){
                // 移除arap不必要的属性
                let editRow = JSON.parse(JSON.stringify(row))
                // 重写属性
                editRow['arap_id'] = editRow.id
                editRow.id = 0
                editRow['arapInfo'] = {
                    amount : editRow['amount'],
                    amount_remain : editRow['amount_remain']
                }
                editRow['amount'] = editRow['amount_remain']
                // 设置今日time
                editRow.dateR = CurrDateR
                editRow.timeR = CurrTimeR
                editRow['tally_time'] = '' // 以当前时间
                editRow.category_id = String(editRow.category_id )
                editRow.account_id = String(editRow.account_id )
                if(editRow.member_id  === 0) editRow.member_id = ''
                if(editRow.store_id  === 0) editRow.store_id = ''
                if(editRow.account_dst_id  === 0) editRow.account_dst_id = ''
                if(editRow.project_id  === 0) editRow.project_id = ''
                editRow.member_id = String(editRow.member_id )
                editRow.store_id = String(editRow.store_id )
                editRow.account_dst_id = String(editRow.account_dst_id )
                editRow.project_id = String(editRow.project_id )
                // 处理附件转换
                this.recordFormEditFileList=[]
                editRow.attachment.forEach(v=>{
                    this.recordFormEditFileList.push({
                        name:v.id,
                        url:v.file_name
                    })
                });

                this.arapForm = editRow
                this.arapDialog = true
            },
            detailArap(row) {
                this.arapId = 0
                this.arapId = row['id']
                this.arapRow = JSON.parse(JSON.stringify(row))
                this.arapDetailsDialog = true
            },
            editRecord(row){
                let editRow = JSON.parse(JSON.stringify(row))
                if(editRow['tally_time'] !== '' ){
                    let timeArr = editRow.tally_time.split(' ')
                    editRow.dateR = timeArr[0]
                    editRow.timeR = timeArr[1]
                }
                editRow.category_id = String(editRow.category_id )
                editRow.account_id = String(editRow.account_id )
                if(editRow.member_id  === 0) editRow.member_id = ''
                if(editRow.store_id  === 0) editRow.store_id = ''
                if(editRow.account_dst_id  === 0) editRow.account_dst_id = ''
                if(editRow.project_id  === 0) editRow.project_id = ''
                editRow.member_id = String(editRow.member_id )
                editRow.store_id = String(editRow.store_id )
                editRow.account_dst_id = String(editRow.account_dst_id )
                editRow.project_id = String(editRow.project_id )
                // 处理附件转换
                this.recordFormEditFileList=[]
                editRow.attachment.forEach(v=>{
                    this.recordFormEditFileList.push({
                        name:v.id,
                        url:v.file_name
                    })
                });
                if(editRow.material_json !== ''){
                    editRow.material_json = JSON.parse(editRow.material_json);
                }else{
                    editRow.material_json = []
                }
                this.recordForm = editRow
                this.recordDialog = true
            },
            auditRecord(row,state){
                let that = this
                let advice = state === 1 ? '同意' : '拒绝'
                let state_txt = state === 1 ? '待核销' : '已忽略'
                this.$confirm('确定要审核该行记录：'+ advice, '提示', {
                    confirmButtonText: '确定',
                    callback: action => {
                        if(action === 'confirm') {
                            let postUrl = '/api/tally-arap/audit'
                            axios.post(postUrl,{id:row.id,state:state},{
                                headers: {'token': loginToken},
                            }).then(function(res) {
                                if(res.data.status === 'success'){
                                    row.state = state
                                    row.state_txt = state_txt
                                    that.$message({
                                        type: 'success',
                                        message: '操作成功~'
                                    })
                                }else{
                                    that.$message({
                                        type: 'error',
                                        message: '解析数据失败:'+res.data.error_message
                                    })
                                }
                            })
                        }
                    }
                });
            },
            delRecord(index,row){
                let that = this
                this.$confirm('确定要删除该行记录？如果存在核销记录请先手动删除，请确认？', '提示', {
                    confirmButtonText: '确定',
                    callback: action => {
                        if(action === 'confirm') {
                            let postUrl = '/api/tally-arap/del'
                            axios.post(postUrl,{id:row['id']},{
                                headers: {'token': loginToken},
                            }).then(function(res) {
                                if(res.data.status === 'success'){
                                    that.$message({
                                        type: 'success',
                                        message: '操作成功~'
                                    })
                                    that.recordList.splice(index, 1)
                                }else{
                                    that.$message({
                                        type: 'error',
                                        message: '解析数据失败:'+res.data.error_message
                                    })
                                }
                            })
                        }
                    }
                })
            }
        }
    }
</script>
<style>
    .hxa{
        color: #3396fa;
    }
    .recordOptBtn{
        cursor: pointer;
    }
    .recOpt .el-button--medium {
        padding: 6px;
        font-weight: normal;
    }
    #tallyRecordBox{
        width:100%;
    }
</style>
